package com.itheima.wms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.wms.common.enums.HandoverStatus;
import com.itheima.wms.common.enums.OutboundStatus;
import com.itheima.wms.common.service.CrudServiceImpl;
import com.itheima.wms.dao.HandoverMapper;
import com.itheima.wms.dao.OutboundListMapper;
import com.itheima.wms.dao.OutboundMapper;
import com.itheima.wms.entity.HandoverEntity;
import com.itheima.wms.entity.OutboundEntity;
import com.itheima.wms.service.HandoverService;
import com.itheima.wms.service.StatusRecordService;
import com.itheima.wms.vo.BatchVO;
import com.itheima.wms.vo.HandoverDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 业务实现类
 * 交接任务
 * </p>
 */
@Slf4j
@Service
public class HandoverServiceImpl extends CrudServiceImpl<HandoverMapper, HandoverEntity> implements HandoverService {

    @Autowired
    private OutboundMapper outboundMapper;
    @Autowired
    private OutboundListMapper outboundListMapper;
    @Autowired
    private StatusRecordService statusRecordService;

    @Override
    @Transactional
    public BatchVO complete(List<Long> ids) {
        BatchVO.BatchVOBuilder batchVOBuilder = BatchVO.builder();
        ids.forEach(id -> {
            HandoverEntity handoverEntity = this.getById(id);

            if (HandoverStatus.HANDOVER.getCode() != handoverEntity.getStatus()) {
                log.info("id:{} 状态不正确", id);
                batchVOBuilder.error(handoverEntity.getCode() + "状态不合法");
                return;
            }

            // 修改交接任务状态 为 交接完成
            handoverEntity.setStatus(HandoverStatus.COMPLETED.getCode());
            handoverEntity.setCompletionTime(LocalDateTime.now());
            this.updateById(handoverEntity);
            statusRecordService.saveStatus(handoverEntity);

            // 修改入库单状态 为 交接完成
            OutboundEntity outboundEntity = outboundMapper.selectById(handoverEntity.getMasterId());
            outboundEntity.setStatus(OutboundStatus.HANDOVER_COMPLETED.getCode());
            outboundMapper.updateById(outboundEntity);
            statusRecordService.saveStatus(outboundEntity);

            batchVOBuilder.result(handoverEntity.getCode());
        });
        return batchVOBuilder.build();
    }

    @Override
    public IPage<HandoverDetailVO> pageDetail(Page<HandoverDetailVO> page, Map data) {
        IPage<HandoverDetailVO> iPage = this.baseMapper.selectHandoverDetail(page, data);
        return iPage;
    }
}

